package com.spring.test_back_end.controller;

import com.spring.test_back_end.bean.Ret;
import com.spring.test_back_end.bean.RetCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private String UPLOADED_FOLDER;

    @Bean
    public static String UPLOADED_FOLDER() {
//        try {
////            File path = new File(ResourceUtils.getURL("classpath:").getPath());
////            if (!path.exists()) path = new File("");
////            return path.getAbsolutePath()+"/";
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//            return "/";
//        }
        return "/";
    }


    @ResponseBody
    @PostMapping("upload")
    public Object singleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Ret.Builder(RetCode.ERROR).err("上传文件不存在").build();
        } else {
            try {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                Files.write(path, bytes);
                Map<String, Object> res = new HashMap<>();
                res.put("url", path);
                return new Ret.Builder(RetCode.SUCCESS).data(res).build();
            } catch (IOException e) {
                e.printStackTrace();
                return new Ret.Builder(RetCode.ERROR).err("上传文件出错").build();
            }
        }
    }
}
